package com.project.fortuneteller.service.impl;

import com.project.fortuneteller.pojo.dto.HeartDto;
import com.project.fortuneteller.utils.Entity;
import com.project.fortuneteller.utils.Result;
import com.project.fortuneteller.utils.ThreeCache;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RFuture;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;


/***
 *
 *  获取实时人数的心跳机制
 * */

@Slf4j
@Service
public class HeartServiceImpl {
    @Resource
    RedissonClient redisson;

    private String userToken;

    /**
     *
     * @param tokenVal
     * @return
     */
    public Result getHeart(String tokenVal){

        this.userToken = tokenVal;
        // 获取 Sorted Set 对象
        RScoredSortedSet<String> leaderboard = redisson.getScoredSortedSet("heart_time");
        // 获取
        BigDecimal current  = new BigDecimal( Double.toString((double) System.currentTimeMillis() / 1000)).setScale(2, RoundingMode.HALF_UP);
        // 获取 用户 token
        Double score = leaderboard.getScore("heart:" + userToken);
        if(score==null){
            leaderboard.add(current.doubleValue(),"heart:" + userToken);
        }
         // 存入 当前 的 时间戳
        leaderboard.addIfExists(current.doubleValue(), "heart:" + userToken);
        Collection<Entity> values = ThreeCache.values();
        for (Entity va:values){
            log.info("------{}------", va.toString());
        }

        log.info(" tokenVal: {}", ThreeCache.size());

        // 获取当前用户数量
        HeartDto heartDto = new HeartDto(true,ThreeCache.size());
        if ( ThreeCache.get(tokenVal) == null){
           heartDto.setCurrentUser(false);
        }
        return  Result.success(heartDto);
    }


    /**
     *  去 redis 里面 扫描 超过 3 分钟没有心跳的 将其删除
     *
     * @param
     * @return
     */
    @Scheduled(fixedRate = 1000 * 5)
    public void toScanRequest(){

        RScoredSortedSet<String> leaderboard = redisson.getScoredSortedSet("heart_time");

        BigDecimal current  = new BigDecimal( Double.toString((double) System.currentTimeMillis() / 1000)).setScale(2, RoundingMode.HALF_UP);

        leaderboard.removeRangeByScore(0, true,current.doubleValue() - 10000 ,  true);

    }


}
